<template>
  <div class="app-container">

    <div class="background">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-s-order" />
              可发放余额
              <div class="text">
                ￥<span style="color:#2979ff">{{ balance.user }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <!-- <el-col :span="8">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-document-remove" />
              营收
              <div class="text">
                ￥<span style="color:#19be6b">{{ balance.earns }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div class="detail">
              <i class="el-icon-bank-card" />
              联胜入款/手续费
              <div class="text">
                ￥<span style="color:#fa3534">{{ balance.amount }}</span>
                <span>/</span>
                <span style="color:#ff9900">{{ balance.fee }}</span>
              </div>
            </div>
          </div>
        </el-col> -->
      </el-row>
    </div>
    <div style="padding-top:10px;">
      <el-date-picker
        v-model="search.date"
        type="daterange"
        placeholder="日期"
        size="medium"
        :editable="false"
        :clearable="false"
        value-format="yyyy/MM/dd"
        @change="filterGenerate();"
      />
      &nbsp;&nbsp;
      <el-button type="success" size="medium" @click="handleOpen">导入发放</el-button>
      <el-button type="warning" size="medium" @click="oneHandleOpen">单个发放</el-button>
      <el-button type="info" size="medium" @click="expressData">导出</el-button>
    </div>
    <el-row style="padding-top:10px">
      <el-table
        v-loading="loading"
        :data="list"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="#" type="index" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.createdTime ) | dateFormat('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="转出账号">
          <template slot-scope="scope">
            <span>{{ scope.row.from.__toString }}</span>
          </template>
        </el-table-column>
        <el-table-column label="汇入账号">
          <template slot-scope="scope">
            <span>{{ scope.row.toValue }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="comment" label="备注" />
        <el-table-column prop="status" label="状态" />
      </el-table>
    </el-row>

    <el-row>
      <div class="block">
        <el-pagination
          :current-page.sync="pager.page"
          :page-sizes="[20, 50, 100, 300]"
          :page-size="pager.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paginator ? paginator.totalCount : 0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-row>

    <el-dialog
      title="转账操作"
      :visible.sync="dialog.visible"
      width="50%"
    >
      <div style="padding: 10px;">
        <div v-if="importUsers.length > 0 && isImport">
          <el-table
            :data="importUsers"
            style="width: 100%"
          >
            <el-table-column
              prop="username"
              label="电话"
            />
            <el-table-column
              prop="amount"
              label="发放金额"
            />
            <el-table-column
              label="发放账号"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.user == ''" style="color:red">用户不存在</div>
                <div v-else>
                  <div v-if="scope.row.account == '' || !scope.row.account" style="color:red">未绑定银行卡</div>
                  <div v-else>
                    <div v-if="scope.row.name != scope.row.account.name" style="color:red">姓名不一致({{ scope.row.name }}/{{ scope.row.account.name }})</div>
                    <div v-else style="color:green">{{ scope.row.account.name }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else>
          <el-form ref="form" label-width="180px">
            <el-form-item label="收款手机号码">
              <el-select
                v-model="inputUser.userId"
                filterable
                remote
                clearable
                placeholder="请输入"
                :remote-method="remoteMethod"
                :loading="inputUser.loading"
                @change="chooseUser($event)"
              >
                <el-option
                  v-for="item in searchUsers"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="收款人姓名">
              <el-input v-model="inputUser.name" :disabled="true" />
            </el-form-item>
            <el-form-item label="转账金额">
              <el-input v-model="inputUser.amount" type="number" min="1" />
            </el-form-item>
          </el-form>
        </div>
        <el-row type="flex" align="middle" style="padding:20px 10px 10px 10px">
          <el-col :span="4"><strong>转账方式</strong></el-col>
          <el-col :span="20">
            <el-radio v-for="(item,index) in dialog.options" :key="index" v-model="dialog.type" :label="item.value">{{ item.label }}</el-radio>
          </el-col>
        </el-row>
        <el-row type="flex" align="middle" style="padding:10px">
          <el-col :span="4"><strong>支付密码</strong></el-col>
          <el-col :span="20">
            <el-input v-model="dialog.password" type="password" show-password />
          </el-col>
        </el-row>
        <el-row v-if="dialog.type === 1" type="flex" align="middle" style="padding:10px">
          <el-col :span="4"><strong>抽取费率(%)</strong></el-col>
          <el-col :span="12">
            <el-input v-model="dialog.platformFeeRate" type="number" />
          </el-col>
          <el-col :span="8">
            <span style="padding: 10px 10px">
              <el-button type="success" size="small" plain @click="defalultRate">默认费率</el-button>
            </span>
          </el-col>
        </el-row>
        <el-row v-if="dialog.type === 1" type="flex" align="middle">
          <el-col :span="4"><strong>示例</strong></el-col>
          <el-col :span="20">
            <div>实际金额的扣减,如发放100的时候</div>
            <div>实际发放为(1-{{ dialog.platformFeeRate }}%)*100</div>
            <div>实际金额{{ (1-(parseFloat(dialog.platformFeeRate)/100))*100 }}</div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 10px;" @click="dialog.visible = false">取消</el-button>
        <el-button slot="reference" type="primary" :loading="dialog.loading" @click="uploadReady()">
          {{ dialog.loading ? '提交中 ...' : '确认' }}
        </el-button>
      </div>
    </el-dialog>

    <div style="display: none">
      <ele-import
        :fields="importButton.fields"
        :filepath="importButton.filepath"
        :request-fn="requestFn"
        :extra-data="importButton.extraData"
        :rules="importButton.rules"
        :tips="importButton.tips"
        :title="importButton.title"
        :visible.sync="importButton.visible"
      />
    </div>
  </div>
</template>

<script>
import EleImport from '@/utils/myImport.vue'
export default {
  components: {
    EleImport
  },
  data() {
    return {
      inputUser: {
        userId: null,
        amount: 1,
        name: '输入手机号码查询',
        user: '',
        account: '',
        loading: false
      },
      searchUsers: [],
      importUsers: [],
      loading: false,
      store: null,
      isImport: false,
      list: [],
      staffs: [],
      search: {
        date: []
      },
      pager: {
        page: 1,
        limit: 20
      },
      paginator: null,
      balance: {
        user: 0,
        earns: 0,
        amount: 0,
        fee: 0
      },
      payment: 'huifu',
      dialog: {
        visible: false,
        type: 2,
        password: null,
        loading: false,
        platformFeeRate: 0,
        options: [{ value: 1, label: '到余额' }, { value: 2, label: '到银行卡' }]
      },
      params: this.$route.query,

      importButton: {
      // 弹窗的标题
        title: '导入模板',
        // 提示信息
        tips: ['请按照模板上传，电话、金额不能为空，否则会导致导入不成功;日期必须使用文本格式;如上传数据出现未设置电话账号，会导致取消上传，请先设置账号'],
        // 假如数据库中是`name`字段, 而Excel模板列是`名字`, 就需要写成 name: '名字'
        // ele-import 内部会抛弃非定义在fields里的列
        fields: {
          username: '电话',
          amount: '汇款金额',
          name: '姓名'
        },
        rules: {
          username: { type: 'number', required: true, message: '电话不能为空' },
          amount: [
            { type: 'number', message: '汇款金额需为数字类型' },
            { required: true, message: '汇款金额不能为空' }
          ]
        },
        filepath: `https://pub.nightkper.com/import.xlsx`,
        // 控制弹窗, 和dialog的visible一样
        // https://element.eleme.cn/#/zh-CN/component/dialog
        visible: false,
        endDate: ''
      }
    }
  },
  async created() {
    if (this.params.date) {
      // date范围 [0]startTime [1]endTime
      this.search.date[0] = this.params.date[0]
      this.search.date[1] = this.params.date[1]
    } else {
      const today = new Date()
      const yesterday = new Date(today.getTime() - 86400000)
      const startTime = `${yesterday.getFullYear()}/${yesterday.getMonth() + 1}/${yesterday.getDate()}`
      this.search.date.push(startTime)
      this.search.date.push(startTime)
    }

    const staffs = await this.axios.get(`/officer/staffs`, { params: {
      '@display': `{
              'id': 'entity.getId()',
              'name': 'entity.getName()',
              'user': 'entity.getUser().getId()'
          }`,
      limit: 10000000
    }})
    if (staffs.data) {
      this.staffs = staffs.data
    }

    const user = await this.axios.get(`/api/user`, { params: {
      '@expands': `['entity.officer.store']`
    }})
    if (!user.data.paymentPassword) {
      this.$message.warning('账号未设置支付密码,请在右上角选择重置支付密码！')
    }
    this.store = user.data.officer?.__metadata.store?.__metadata
    console.log('store', this.store)
    if (!this.store.user) {
      this.$message.error('获取主账号信息失败！')
      return
    }
    if (this.store.defaultPayment === 'huifu-pay') {
      this.payment = 'huifu'
    } else {
      this.payment = 'fuiou'
    }
    // this.defalultRate()
    this.filterGenerate()
  },
  methods: {
    // 根据电话号码查找账号
    remoteMethod(query) {
      if (query !== '') {
        this.inputUser.loading = true
        this.axios.get(`/officer/users`, { params: {
          '@filter': `entity.getEnabled() == true && entity.getUsername() matches "${query}"`
        }}).then((res) => {
          const list = []
          for (var i of res.data) {
            if (i.username === 'admin' || i.username === 'platform') {
              continue
            }
            list.push(i)
          }
          this.searchUsers = list
        }).finally(() => {
          this.inputUser.loading = false
        })
      } else {
        this.searchUsers = []
      }
    },
    // 选择账号时获取account
    chooseUser(e) {
      const user = this.searchUsers.find(v => v.id === e)
      if (!user) {
        this.$message.error('获取收款账号电话号码')
        return
      }
      this.inputUser.user = user
      this.axios.get(`/officer/staffs`, { params: {
        '@filter': `entity.getUser().getId() == ${user.id}`
      }}).then((res) => {
        if (res.data.length > 0) {
          this.inputUser.name = res.data[0].name
        } else {
          this.$message.error('只能汇款到本场所的员工账号！')
          return
        }
        // 再查银行卡信息
        if (this.payment === 'fuiou') {
          this.axios.get(`/officer/fuiou-accounts/from-user/${user.id}`).then((res) => {
            if (res.data !== '' && res.data !== false) {
              this.inputUser.account = res.data
              this.inputUser.name += `(绑定银行账号:${res.data.name})`
            } else {
              this.inputUser.name += '(无绑定银行卡)'
              this.inputUser.account = ''
            }
          })
        } else {
          this.axios.get(`/officer/huifu-accounts/from-user/${user.id}`).then((res) => {
            console.log('汇付账号', res.data)
            if (res.data !== '' && res.data !== false) {
              this.inputUser.account = res.data
              this.inputUser.name += `(绑定银行账号:${res.data.name})`
            } else {
              this.inputUser.name += '(无绑定银行卡)'
              this.inputUser.account = ''
            }
          })
        }
      })
    },
    // 单个发放，公用一个组件，只是名单自己输入还是用导入输入而已
    oneHandleOpen() {
      this.isImport = false
      this.importUsers = []
      this.dialog.visible = true
    },
    defalultRate() {
      const platformFeeRate = this.store.config && this.store.config.transactionFeeRate ? this.store.config.transactionFeeRate : 0
      this.dialog.platformFeeRate = (platformFeeRate * 100).toFixed(2)
    },
    uploadReady() {
      if (!this.dialog.password) {
        this.$message.error('请输入验证密码')
        return
      }
      if (this.dialog.platformFeeRate > 100 || this.dialog.platformFeeRate < 0) {
        this.$message.error('抽取费率应在0-100之间')
        return
      }
      this.dialog.loading = true
      // 单个编写的，塞入去
      if (!this.isImport) {
        this.importUsers = [this.inputUser]
      }
      if (this.importUsers.length === 0) {
        this.$message.error('无汇款信息！')
        return
      }
      // 先循环数据，没有user的，直接断，如果提现到银行卡的，没有绑定银行卡的，都断
      let noUser = false
      let noAccount = false
      for (var i of this.importUsers) {
        if (i.user === '') {
          noUser = true
        }
        if (!i.account) {
          noAccount = true
        }
      }
      if (noUser) {
        this.$message.error('存在无账号记录，请先删除再重新导入！')
        this.dialog.loading = false
        return
      }
      if (noAccount && this.dialog.type === 2) {
        this.$message.error('有账号未绑定银行卡，不能转赠到银行卡！')
        this.dialog.loading = false
        return
      }

      this.axios.post(`/api/user/validate-password`, {
        password: this.dialog.password,
        payment: 1 })
        .then(res => {
          // 都过的，整理date先转账，如果是提现到银行卡，再提现
          const sendData = []
          const withdrawData = []
          const customFeeRate = Number(this.dialog.platformFeeRate) / 100
          if (this.dialog.type === 2) {
            this.importUsers.map(i => {
              sendData.push({
                to: i.user.id, amount: i.amount, type: 'upload', comment: '导入发放'
              })
              withdrawData.push({
                user: i.user.id,
                amount: i.amount,
                payment: this.payment,
                immediately: false
              })
            })
          } else {
            this.importUsers.map(i => {
              sendData.push({
                to: i.user.id, amount: (Number(i.amount) * (1 - customFeeRate)).toFixed(2), type: 'upload', comment: '导入发放'
              })
              // withdrawData.push({
              //   user: i.user.id, amount: (Number(i.amount) * (1 - customFeeRate)).toFixed(2)
              // })
            })
          }
          this.axios.post(`/officer/transactions/send`, sendData)
            .then((res) => {
              if (this.dialog.type === 2) {
                this.axios.post(`/officer/withdraws`, withdrawData, { params: { '@partial': true }}).then((res) => {
                  this.dialog.password = null
                  this.dialog.visible = false
                  this.getBalance()
                  this.dataProcessor()
                // this.importButton.visible = true
                })
              } else {
                this.dialog.password = null
                this.dialog.visible = false
                this.getBalance()
                this.dataProcessor()
              // this.importButton.visible = true
              }
            }).catch((err) => {
              this.$message.err(err.message)
            })
        })
        .finally(() => { this.dialog.loading = false })
    },
    getBalance() {
      if (this.store.user) {
        this.axios.get(`/officer/balances`, { params: {
          '@filter': `entity.getUser().getId() == ${this.store.user.id}`
        }}).then(res => {
          if (res.data.length > 0 && res.data[0].amount) {
            this.balance.user = res.data[0].amount
          } else {
            this.balance.user = 0
          }
        })
      }

      this.axios.get(`/officer/stores/statistics`, { params: {
        after: `${this.search.date[0]} 08:00:00`,
        before: `${this.endDate} 07:59:59`
      }}).then((res) => {
        if (res.data) {
          this.balance.earns = res.data.earns
        } else {
          this.balance.earns = 0
        }
      })

      // 查呢个store对应的所有pos设备，并且查入金账户，进行手续费核查
      this.axios.get(`/officer/fuiou-pos-devices`).then((res) => {
        const targetUsers = [this.store.user.id]
        for (var i of res.data) {
          targetUsers.push(i.targetUser.id)
        }
        let depositFilter = ''
        let transactionFilter = ''
        for (var j in targetUsers) {
          if (parseInt(j) === 0) {
            transactionFilter = ` (entity.getFrom().getId() == ${targetUsers[j]}`
            depositFilter = ` (entity.getUser().getId() == ${targetUsers[j]}`
          } else {
            transactionFilter += ` || entity.getFrom().getId() == ${targetUsers[j]}`
            depositFilter += ` || entity.getUser().getId() == ${targetUsers[j]}`
          }
          if (parseInt(j) === targetUsers.length - 1) {
            transactionFilter += ')'
            depositFilter += ')'
          }
        }
        this.axios.get(`/officer/deposits`, { params: {
          '@filter': `entity.getStatus() == 1 && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') && entity.getCreatedTime() <= datetime.get('${this.endDate} 07:59:59') && ${depositFilter}`,
          '@select': `SUM(entity.amount) as amount`
        }}).then((res) => {
          if (res.data.length > 0 && res.data[0].amount) {
            this.balance.amount = res.data[0].amount
          } else {
            this.balance.amount = 0
          }
        })

        // 手续费
        this.axios.get(`/officer/transactions`, { params: {
          '@filter': `entity.getType() == "deposit-fee"
                    && ${transactionFilter}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${this.search.date[1]} 07:59:59')`,
          '@select': `SUM(entity.amount) as amount`
        }}).then((res) => {
          if (res.data.length > 0 && res.data[0].amount) {
            this.balance.fee = res.data[0].amount
          } else {
            this.balance.fee = 0
          }
        })
      })
    },
    filterGenerate() {
      const nextDate = new Date(new Date(this.search.date[1]).getTime() + 86400000)
      const endDate = `${nextDate.getFullYear()}/${nextDate.getMonth() + 1}/${nextDate.getDate()}`
      this.endDate = endDate
      this.filter = {
        '@filter': `entity.getType() == "upload" 
                    && entity.getFrom().getId() == ${this.store.user.id}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${endDate} 07:59:59')`,
        '@order': 'entity.id|DESC'
      }
      this.dataProcessor()
    },
    dataProcessor() {
      this.getBalance()
      this.loading = true
      // table数据
      this.axios.get(`/officer/transactions`, {
        params: Object.assign(
          {},
          this.filter,
          this.pager
        )
      }).then(res => {
        const list = []
        for (var i of res.data) {
          if (i.amount > 0) {
            const staff = this.staffs.find(v => v.user === i.to.id)
            if (staff) {
              i.toValue = `${i.to.__toString}(${staff.name})`
            } else {
              i.toValue = i.to.__toString
            }
            list.push(i)
          }
        }
        this.list = list
        this.loading = false
        this.paginator = res.paginator
      })
    },
    expressData() {
      const loading = this.$loading({
        lock: true,
        text: '数据导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.axios.get(`/officer/transactions`, {
        params: {
          '@filter': `entity.getType() == "upload" 
                    && entity.getFrom().getId() == ${this.store.user.id}
                    && entity.getCreatedTime() >= datetime.get('${this.search.date[0]} 08:00:00') 
                    && entity.getCreatedTime() <= datetime.get('${this.endDate} 07:59:59')`,
          limit: 10000
        }
      }).then(res => {
        const list = []
        for (var i of res.data) {
          if (i.amount > 0) {
            const staff = this.staffs.find(v => v.user === i.to.id)
            let createdTime = new Date(i.createdTime)
            createdTime = `${createdTime.getFullYear()}/${createdTime.getMonth() + 1}/${createdTime.getDate()} ${createdTime.getHours()}:${createdTime.getMinutes()}:${createdTime.getSeconds()}`
            const item = {
              createdTime: createdTime,
              from: i.from.__toString,
              amount: i.amount,
              comment: i.comment
            }
            if (staff) {
              item['toValue'] = `${i.to.__toString}(${staff.name})`
            } else {
              item['toValue'] = i.to.__toString
            }
            list.push(item)
          }
        }
        console.log('数据', list)
        const label = {
          createdTime: '转账时间',
          from: '装出账号',
          toValue: '转入账号',
          amount: '转账金额',
          comment: '转账备注'
        }
        const exportExcelCsv = require('@/utils/exportExcelCsv').default
        exportExcelCsv(label, list, `export-settle-item.csv`)
        loading.close()
      })
    },
    // Pager size changed
    handleSizeChange(val) {
      // this.pager.limit = val
      // this.dataProcessor()
    },

    // Pager page changed
    handleCurrentChange(val) {
      // this.pager.page = val
      // this.dataProcessor()
    },

    // requestFn函数会被注入请求的数据
    // 需要返回一个Promise对象
    async requestFn(data) {
      if (data.length === 0) {
        this.$message.error('请填写导入信息！')
      }
      const users = []
      const promise = []
      for (var i of data) {
        promise.push(
          this.axios.get(`/officer/users`, { params: {
            '@filter': `entity.getUsername() == ${i.username}`
          }}).then((res) => {
            if (res.data.length === 0) {
              users.push({
                username: i.username,
                amount: i.amount,
                name: i.name,
                user: ''
              })
            } else {
              users.push({
                username: i.username,
                amount: i.amount,
                name: i.name,
                user: res.data[0]
              })
            }
          })
        )
      }
      Promise.all(promise).then((res) => {
        const promise2 = []
        for (var i in users) {
          if (users[i].user !== '') {
            promise2.push(
              this.axios.get(`/officer/fuiou-accounts/from-user/${users[i].user.id}`).then((res) => {
                if (res.data !== '') {
                  users[i]['account'] = res.data
                } else {
                  users[i]['account'] = ''
                }
              })
            )
          } else {
            users[i]['account'] = ''
          }
        }
        Promise.all(promise2).then((res) => {
          this.importButton.visible = false
          this.dialog.visible = true
          this.importUsers = users
        })
      })
    },
    handleCloseImport() {
      console.log('组件关闭了~')
      // this.defalultRate()
      this.dataProcessor()
    },
    handleFinishImport() {
      console.log('导入完毕了~')
      // this.defalultRate()
      this.dataProcessor()
    },
    handleOpen() {
      this.isImport = true
      this.importButton.visible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.background {
  background-color: #f0f0f0;
  padding: 15px;
  border-radius: 10px;
}
.detail {
  background-color: white;
  padding: 20px;
  text-align: center;
}
.text {
  font-size: 24px;
  padding-top: 10px;
}
</style>
